package com.dougs.timehandler;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.dougs.timehandler.databinding.FragmentLockSetupBinding;
import com.dougs.timehandler.receiver.LockDeviceAdminReceiver;
import com.dougs.timehandler.service.LockForegroundService;
import com.google.android.material.snackbar.Snackbar;

public class LockSetupFragment extends Fragment {

    private FragmentLockSetupBinding binding;

    private int REQUEST_CODE_ENABLE_ADMIN = 10001;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentLockSetupBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.buttonLockSetup.setOnClickListener(view1 -> {
            String text = binding.edittextLockMin.getText().toString();
            if("".equals(text)){
                Snackbar.make(view1,  "请设置锁屏时间！", Snackbar.LENGTH_LONG)
                        .setAction("必填", null).show();
                return;
            }

            //激活设备管理
            this.activateDeviceAdmin();

            Snackbar.make(view1, text + "分钟后锁屏！", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();

            int lockTime = Integer.parseInt(text);

            //启动前台服务
            Intent startServiceIntent = new Intent(getContext(), LockForegroundService.class);
            startServiceIntent.putExtra("lockTime", lockTime);
            getContext().startService(startServiceIntent);

            //跳转到倒计时页面
            Bundle arguments = new Bundle();
            arguments.putInt("lockTime", lockTime);
            NavHostFragment.findNavController(LockSetupFragment.this)
                    .navigate(R.id.action_LockSetup_to_LockCounter, arguments);
        });
    }

    //TODO 替换startActivityForResult
    public void activateDeviceAdmin() {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        ComponentName componentName = new ComponentName(getContext(), LockDeviceAdminReceiver.class);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
    }

   @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}